package com.ofek.eventos.util;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class IOUtils {
	public static void writeLine(final String line,final File where,final boolean append) {
		try {
			final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(where,append));
			bufferedWriter.write(line);
			bufferedWriter.newLine();
			bufferedWriter.close();
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}
	public static String toBase64(final String str) throws Exception {
		final byte[] encoded = android.util.Base64.encode(str.getBytes(),android.util.Base64.DEFAULT);
		return new String(encoded);
	}
	public static String fromBase64(final String str) throws Exception {
		final byte[] decoded = android.util.Base64.decode(str.getBytes(),android.util.Base64.DEFAULT);  
		return  new String(decoded);
	}

	public static String objectToString(final Serializable object) {
		String encoded = null;

		try {
			final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			objectOutputStream.close();
			encoded = new String(android.util.Base64.encode(byteArrayOutputStream.toByteArray(),android.util.Base64.DEFAULT));
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return encoded;
	}


	public static <T extends Serializable> T stringToObject(final String string, final Class<T> clazz) {
		final byte[] bytes = android.util.Base64.decode(string.getBytes(),android.util.Base64.DEFAULT);
		T object = null;
		try {
			final ObjectInputStream objectInputStream = new ObjectInputStream( new ByteArrayInputStream(bytes) );
			object = (T)objectInputStream.readObject();
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return object;
	}
}
